# -*- coding: utf-8 -*-
# @Time    : 2019-08-09 14:24
# @Author  : kbsonlong
# @Email   : kbsonlong@gmail.com
# @Blog    : www.alongparty.cn
# @File    : blog_tags.py
# @Software: PyCharm

from django import template
from ..models import Article, Category, Tag, Carousel, FriendLink, Activate, Keyword
from django.db.models.aggregates import Count
from django.utils.html import mark_safe
import re

# 注册自定义标签函数
register = template.Library()



# 返回文章分类查询集
@register.simple_tag
def get_category_list(id):
    """分类列表"""
    return Category.objects.filter(category_id=id)


@register.simple_tag
def get_top_category_list():
    """分类列表"""
    return Category.objects.filter(is_tab=True).order_by('-id')

##返回轮播图
@register.simple_tag
def get_carousel_index():
    return Carousel.objects.filter(number__lte=5)


# 获取热门排行数据查询集，参数：sort 文章类型， num 数量
@register.simple_tag
def get_article_list(sort=None, num=None):

    if sort:
        if num:
            return Article.objects.order_by(sort)[:num]
        return Article.objects.order_by(sort)
    if num:
        return Article.objects.all()[:num]
    return Article.objects.all()

# 获取归档文章查询集
@register.simple_tag
def get_data_date():
    """获取文章发表的不同月份"""
    article_dates = Article.objects.datetimes('create_time', 'month', order='DESC')
    return article_dates


# 返回标签查询集
@register.simple_tag
def get_tag_list():
    """返回标签列表"""
    return Tag.objects.annotate(total_num=Count('article')).filter(total_num__gt=0)


# 返回博文标签查询集
@register.simple_tag
def get_article_tags(article_pk):
    """返回标签列表"""
    article = Article.objects.filter(pk=article_pk).first()
    tags = Tag.objects.filter(article=article)
    return tags

# 返回活跃的友情链接查询集
@register.simple_tag
def get_friends():
    """获取活跃的友情链接"""
    return FriendLink.objects.filter(is_show=True, is_active=True)


# 获取文章详情页下方的推荐阅读文章
@register.simple_tag
def get_category_article():
    article_4 = get_article_list('views', 4)
    article_8 = get_article_list('views', 8)
    return {'article_4': article_4, 'article_8': article_8}


# 获取文章详情页下方的推荐阅读文章
@register.simple_tag
def get_next_article(article_pk):
    article = Article.objects.filter(pk=article_pk).first()
    has_previous = False
    id_previous = int(article_pk) - 1
    has_next = False
    id_next = int(article_pk) + 1
    article_prev = None
    article_next = None
    # while not has_previous and id_previous >= 1:
    #     article_prev = Article.objects.filter(pk=id_previous).first()
    #     if not article_prev:
    #         id_previous -= 1
    #     else:
    #         has_previous = True
    # while not has_next and id_next >= 1:
    #     article_next = Article.objects.filter(pk=id_previous).first()
    #     if not article_next:
    #         id_next -= 1
    #     else:
    #         has_next = True
    article_prev = Article.objects.filter(pk=id_previous).first()
    article_next = Article.objects.filter(pk=id_previous).first()
    return { 'article_prev': article_prev,'article_next':article_next}

# 返回公告查询集
@register.simple_tag
def get_active():
    """"获取公告内容"""
    text = Activate.objects.filter(is_active=True)
    if text:
        text = text[0].text
    else:
        text = ''
    return mark_safe(text)

@register.simple_tag
def my_highlight(text, q):
    """自定义标题搜索词高亮函数，忽略大小写"""
    if len(q) > 1:
        try:
            text = re.sub(q, lambda a: '<span class="highlighted">{}</span>'.format(a.group()),
                          text, flags=re.IGNORECASE)
            text = mark_safe(text)
        except:
            pass
    return text